package com.cc.mydlnademo

import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.cc.dlnalib.DLNAController
import com.cc.dlnalib.DLNAUtil
import com.cc.dlnalib.isWifiConnected
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.cybergarage.upnp.Device

class AudioListFragment : Fragment() {
    private var audioList = mutableListOf<AudioData>()
    private lateinit var liveView: ListView
    private lateinit var playViewModel: PlayViewModel

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        playViewModel = ViewModelProvider(
            activity!!,
            ViewModelProvider.NewInstanceFactory()
        ).get(PlayViewModel::class.java)
        liveView = ListView(context)
        liveView.divider = GradientDrawable().also {
            it.setSize(10000, 1)
            it.setColor(Color.GRAY)
        }
        return liveView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        GlobalScope.launch {
            val list = context?.getLocalAudio()
            audioList.clear()
            withContext(Dispatchers.Main) {
                list?.let {
                    audioList.addAll(it)
                    liveView.adapter = object : BaseAdapter() {
                        override fun getView(
                            position: Int,
                            convertView: View?,
                            parent: ViewGroup
                        ): View {
                            val itemView: View =
                                convertView
                                    ?: LayoutInflater.from(context)
                                        .inflate(android.R.layout.simple_list_item_1, parent, false)
                            val audioData = getItem(position)
                            val textView = (itemView as TextView)
                            textView.compoundDrawablePadding = 10
                            textView.text = audioData.title
                            val isPlaying =
                                playViewModel.getCurrentPath() == audioData.path
                            val drawable =
                                if (isPlaying) {
                                    textView.setTextColor(resources.getColor(R.color.red))
                                    resources.getDrawable(R.drawable.ic_playing_tip)
                                } else {
                                    textView.setTextColor(resources.getColor(R.color.black))
                                    null
                                }
                            textView.setCompoundDrawablesWithIntrinsicBounds(
                                drawable,
                                null,
                                null,
                                null
                            )
                            return itemView
                        }

                        override fun getItem(position: Int): AudioData {
                            return it[position]
                        }

                        override fun getItemId(position: Int): Long {
                            return 0
                        }

                        override fun getCount(): Int {
                            return it.size
                        }
                    }
                    playViewModel.indexLiveData.observe(this@AudioListFragment, Observer {
                        GlobalScope.launch(Dispatchers.Main) {
                            (liveView.adapter as BaseAdapter).notifyDataSetChanged()
                        }
                    })
                    liveView.setOnItemClickListener { parent, view, position, id ->
                        if (!context!!.isWifiConnected()) {
                            Toast.makeText(context, "请连接WIFI", Toast.LENGTH_SHORT).show()
                            return@setOnItemClickListener
                        }
                        val audioData = list[position]
                        fun play(device: Device, audioData: AudioData) {
                            playViewModel.deviceLiveData.value = device
                            playViewModel.audioListData.value = audioList
                            playViewModel.play(device, audioData) {
                                Toast.makeText(context, "投屏成功", Toast.LENGTH_SHORT).show()
                                (activity as MainActivity).showPlaying()
                            }
                        }
                        if (DLNAController.currentDevice == null) {
                            DLNAUtil.showDLNADialog(activity!!) { devide ->
                                play(devide, audioData)
                                null
                            }
                        } else {
                            play(DLNAController.currentDevice!!, audioData)
                        }
                    }
                }
            }
        }
    }

}
